package com.youhome.mobile.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * Created by chen365 on 2018/09/12.
 */
public class SMSAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SMSAuthenticationToken authenticationToken = (SMSAuthenticationToken) authentication;
        //调用自定义的userDetailsService认证
        //UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
        UserDetails user = (UserDetails) authenticationToken.getPrincipal();

        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        //如果user不为空重新构建SmsCodeAuthenticationToken（已认证）
        SMSAuthenticationToken authenticationResult = new SMSAuthenticationToken(user, user.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return SMSAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
